package com.xjm.i1.core.struct.node.write;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.xjm.i1.constant.ColorEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;

/**
 * 导出Excel数据中数据集合公共字段
 **/
@NoArgsConstructor
@Data
public class AbstractExcelCollection {
    private String deviceId;

    private String env;

    private String pageId;

    @ExcelProperty("color")
    private WriteCellData<String> color;

    public AbstractExcelCollection(String deviceId, String env, String pageId, ColorEnum color) {
        this.deviceId = deviceId;
        this.env = env;
        this.pageId = pageId;
        this.setColor(color);
    }

    /**
     * 分组字段
     * */
    public String group() {
        return this.getColor().getStringValue();
    }

    public void setColor(ColorEnum color) {
        if (color == null) {
            this.color = null;
            return;
        }
        WriteCellData<String> writeCellStyle = new WriteCellData<>();
        writeCellStyle.setStringValue(color.getVal());
        writeCellStyle.setType(CellDataTypeEnum.STRING);
        WriteCellStyle writeCellStyleData = new WriteCellStyle();
        writeCellStyle.setWriteCellStyle(writeCellStyleData);
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.
        writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景,黑色就设置字体为白色
        writeCellStyleData.setFillForegroundColor(color.getIndexedColor().getIndex());
        if (color.getIndexedColor().equals(IndexedColors.GREY_80_PERCENT)) {
            WriteFont writeFont = new WriteFont();
            writeFont.setColor(IndexedColors.WHITE.getIndex());
            writeCellStyleData.setWriteFont(writeFont);
        }
        this.color = writeCellStyle;
    }

    public void setColor(String color) {
        ColorEnum colorEnum = ColorEnum.getColorEnumByVal(color);
        if (ObjectUtil.isNull(colorEnum)) {
            this.color = null;
        } else {
            this.setColor(colorEnum);
        }
    }
}
